package com.yvon.maple.cloud.web.data;

import com.yvon.boot.mybatis.IBaseService;
import com.yvon.boot.mybatis.page.ListData;
import com.yvon.boot.common.result.ResponseData;
import com.yvon.boot.mybatis.search.PageQuery;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 基础 crud controller
 *
 * @author : Yvon
 * @since : 2021-09-24
 */
public abstract class BaseCrudController<E, D, V, S extends IBaseService<E>> extends AbstractController<E, D, V, S> {

    public BaseCrudController() {

    }

    @PostMapping
    @ApiOperation(
        value = "新增",
        notes = "新增API"
    )
    public ResponseData<D> add(@RequestBody V vo) {

        E entity = this.voToEntity(vo);
        getService().save(entity);
        return success(this.entityToDto(entity));
    }

    @PutMapping
    @ApiOperation(
        value = "更新",
        notes = "更新API"
    )
    public ResponseData<D> update(@RequestBody V vo) {
        E entity = this.voToEntity(vo);
        getService().updateById(entity);
        return success(this.entityToDto(entity));
    }

    @DeleteMapping
    @ApiOperation(
        value = "删除",
        notes = "删除API"
    )
    public ResponseData deleteByIds(@RequestBody List<String> ids) {
        return result(getService().removeByIds(ids));
    }

    @GetMapping({"/id/{id}"})
    @ApiOperation(
        value = "根据编号查询信息",
        notes = "根据编号查询信息API"
    )
    public ResponseData<D> getById(@PathVariable("id") String id) {
        E entity = getService().getById(id);
        return success(this.entityToDto(entity));
    }

    @GetMapping({"page"})
    @ApiOperation(
        value = "分页查询",
        notes = "分页查询API"
    )
    public ResponseData<ListData<D>> page(PageQuery pageQuery) {
        ListData listData = getService().page(pageQuery);
        listData.setList(this.entityToDto(listData.getList()));
        return success(listData);
    }

}
